import { useState } from 'react'
import { aiAPI } from '../services/api'

export default function SmartParseTestPage() {
  const [text, setText] = useState('今天下班前准备好明天的会议资料')
  const [loading, setLoading] = useState(false)
  const [resp, setResp] = useState<any>(null)
  const [error, setError] = useState<string | null>(null)
  const [startedAt, setStartedAt] = useState<number | null>(null)
  const [endedAt, setEndedAt] = useState<number | null>(null)

  const samples = [
    '今天下班前准备好明天的会议资料',
    '明天下午3点和客户开会',
    '大后天提交周报',
    '本周五之前完成代码评审',
    '每周一上午9点例会',
    '今天晚上8点健身1小时',
  ]

  const handleRun = async () => {
    if (!text.trim()) return
    setError(null)
    setResp(null)
    setStartedAt(Date.now())
    setEndedAt(null)
    setLoading(true)
    try {
      const r = await aiAPI.smartParse(text.trim())
      setResp(r)
    } catch (e: any) {
      setError(e?.message || '请求失败')
    } finally {
      setEndedAt(Date.now())
      setLoading(false)
    }
  }

  const jsonPretty = (obj: any) => {
    try { return JSON.stringify(obj, null, 2) } catch { return String(obj) }
  }

  // 保留备用：通用本地化时间（当前展示改为 getLocalDateTimeDisplay）

  // 将 ISO 日期与可选的 dueTime 组合为本地 "YYYY-MM-DD HH:mm"
  const getLocalDateTimeDisplay = (iso?: string | null, time?: string | null) => {
    if (!iso) return ''
    const d = new Date(iso)
    if (isNaN(d.getTime())) return String(iso)
    const y = d.getFullYear()
    const m = String(d.getMonth() + 1).padStart(2, '0')
    const day = String(d.getDate()).padStart(2, '0')
    if (time && /^\d{2}:\d{2}$/.test(time)) {
      return `${y}-${m}-${day} ${time}`
    }
    const hh = String(d.getHours()).padStart(2, '0')
    const mm = String(d.getMinutes()).padStart(2, '0')
    return `${y}-${m}-${day} ${hh}:${mm}`
  }

  const result = resp?.result
  const duration = startedAt && endedAt ? `${endedAt - startedAt} ms` : ''

  return (
    <div className="px-4 py-4 space-y-4 max-w-4xl mx-auto">
      <h1 className="text-lg font-semibold text-slate-900">AI 智能解析测试</h1>

      <div className="bg-white rounded-2xl border border-slate-200 p-4 space-y-3">
        <div className="text-sm text-slate-600">输入自然语言，调用 /api/ai/smart-parse，查看输入/输出与解析字段。</div>

        <div className="flex flex-wrap gap-2">
          {samples.map((s, i) => (
            <button key={i} onClick={() => setText(s)} className="px-2 py-1 rounded-lg bg-slate-100 text-slate-700 hover:bg-slate-200 text-xs">
              {s}
            </button>
          ))}
        </div>

        <textarea
          rows={3}
          value={text}
          onChange={(e) => setText(e.target.value)}
          placeholder="输入待解析的语句..."
          className="w-full mt-2 text-sm rounded-xl border border-slate-300 px-3 py-2 focus:outline-none focus:border-blue-500"
        />

        <div className="flex items-center gap-2">
          <button onClick={handleRun} disabled={loading || !text.trim()} className="px-3 py-2 rounded-lg text-white bg-blue-600 hover:bg-blue-700 disabled:opacity-50 text-sm">
            {loading ? '解析中...' : '调用AI解析'}
          </button>
          {duration && <span className="text-xs text-slate-500">耗时: {duration}</span>}
        </div>
      </div>

      {error && (
        <div className="bg-red-50 text-red-700 border border-red-200 p-3 rounded-xl text-sm">{error}</div>
      )}

      {resp && (
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div className="bg-white rounded-2xl border border-slate-200 p-4 space-y-2">
            <h2 className="text-sm font-semibold text-slate-900">解析字段</h2>
            <div className="text-xs text-slate-600">直观查看主要字段结果</div>
            <div className="mt-2 space-y-1 text-sm">
              <div><span className="text-slate-500">标题：</span><span className="font-medium">{result?.title || '-'}</span></div>
              <div><span className="text-slate-500">截止日期 (ISO)：</span>{result?.dueDate || '-'}</div>
              <div><span className="text-slate-500">截止日期 (本地)：</span>{getLocalDateTimeDisplay(result?.dueDate, result?.dueTime)}</div>
              <div><span className="text-slate-500">具体时间：</span>{result?.dueTime || '-'}</div>
              <div><span className="text-slate-500">优先级：</span>{result?.priority || '-'}</div>
              <div><span className="text-slate-500">分类：</span>{result?.category || '-'}</div>
              <div><span className="text-slate-500">标签：</span>{Array.isArray(result?.tags) ? result.tags.join(', ') : '-'}</div>
              <div><span className="text-slate-500">备注：</span>{result?.notes || '-'}</div>
              <div><span className="text-slate-500">是否重复：</span>{String(result?.isRecurring ?? '-')}</div>
              <div><span className="text-slate-500">时间提示：</span>{result?.timeHints ? jsonPretty(result.timeHints) : '-'}</div>
            </div>
          </div>

          <div className="bg-white rounded-2xl border border-slate-200 p-4 space-y-2">
            <h2 className="text-sm font-semibold text-slate-900">原始响应</h2>
            <div className="text-xs text-slate-600">显示后端完整返回（success/result/message/warning）</div>
            <pre className="mt-2 text-xs bg-slate-50 rounded-xl p-3 overflow-auto max-h-96">{jsonPretty(resp)}</pre>
          </div>

          <div className="bg-white rounded-2xl border border-slate-200 p-4 space-y-2 md:col-span-2">
            <h2 className="text-sm font-semibold text-slate-900">请求体</h2>
            <div className="text-xs text-slate-600">POST /api/ai/smart-parse</div>
            <pre className="mt-2 text-xs bg-slate-50 rounded-xl p-3 overflow-auto">{jsonPretty({ text })}</pre>
          </div>

          {resp?.debug?.prompt && (
            <div className="bg-white rounded-2xl border border-amber-200 p-4 space-y-2 md:col-span-2">
              <h2 className="text-sm font-semibold text-amber-900">调试：AI提示词（仅在DEBUG_AI_PROMPT=true时返回）</h2>
              <pre className="mt-2 text-xs bg-amber-50 rounded-xl p-3 overflow-auto max-h-96">{resp.debug.prompt}</pre>
            </div>
          )}
        </div>
      )}
    </div>
  )
}


